﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Coravel.Invocable;
using CRM.Models.Email;
using CRM.Services.Email;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace CRM.Jobs
{
    public class TrackSendTaskStatusJob : IInvocable
    {
        private readonly MyDbContext _dbContext;
        private readonly ILogger<TrackSendTaskStatusJob> _logger;
        private readonly RushMailApplicationService _rushMailApplicationService;

        public TrackSendTaskStatusJob(MyDbContext dbContext, ILogger<TrackSendTaskStatusJob> logger, RushMailApplicationService rushMailApplicationService)
        {
            _dbContext = dbContext;
            _logger = logger;
            _rushMailApplicationService = rushMailApplicationService;
        }
        public async Task Invoke()
        {
            var last24Hours = DateTime.Now.AddDays(-1);
            var needToTrack = await _dbContext.RushMailLinks
                .Where(m => m.State == RushMailState.Send && m.TaskId > 0) // 已完成
                .OrderBy(l => l.LatestTrackTime)
                .Take(20)
                .ToListAsync();
            foreach (var item in needToTrack)
            {
                try
                {
                    await _rushMailApplicationService.TrackSendNumAsync(item);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "跟踪邮件任务发送状态失败, {ItemId}", item.Id);
                }
            }
        }
    }
}